import React, { useState } from 'react'
import { adminnameExist,register } from '../../services/admin'
import { useNavigate } from "react-router-dom";


export default function (props) {
    const navigate = useNavigate();
    const handleReg =  async () => {
        if(adminName.info==='√'&&adminPassword.info==='√'&&ensureAdminPassword.info==='√'){
            await register({adminName:adminName.value,adminPassword:adminPassword.value})
            navigate('/login')
        }else{
            setRegState('注册失败！')
        }
    }
    const [regState,setRegState] = useState('')
    const [adminName, setAdminName] = useState({
        info:'账号由4-20位字符组成',
        value:''
    })
    const [adminPassword, setAdminPassword] = useState({
        info:'密码由6-20位字符组成',
        value:''
    })
    const [ensureAdminPassword, setEnsureAdminPassword] = useState({
        info:'确认密码必须和密码保持一致',
        value:''
    })

    const saveAdminName = async (e) => {
        let result = await adminnameExist(e.target.value)
        if(/^\w{4,20}$/.test(e.target.value)){
            result.code==='0'?setAdminName({info:'√',value:e.target.value}):
            setAdminName({info:result.message,value:e.target.value})
        }else{
            setAdminName({info:'×',value:e.target.value})
        }
        
    }
    const saveAdminPassword = (e) => {
        if (/^\w{6,20}$/.test(e.target.value)&&e.target.value!=='') {
            setAdminPassword({info:'√',value:e.target.value})
        } else {
            setAdminPassword({info:'×',value:e.target.value})
        }
    }
    const saveEnsureAdminPassword = (e) => {
        console.log(e.target.value,adminPassword)
        if (e.target.value === adminPassword.value) {
            setEnsureAdminPassword({info:'√',value:e.target.value})
        } else {
            setEnsureAdminPassword({info:'×',value:e.target.value})
        }
    }
    return (
        <div>
            <p>
                <label>账号：</label>
                <input type='text' onBlur={saveAdminName} />
                <span>{adminName.info}</span>
            </p>

            <p>
                <label>密码：</label>
                <input type='password' onBlur={saveAdminPassword} />
                <span>{adminPassword.info}</span>
            </p>
            <p>
                <label>确认密码：</label>
                <input type='password' onBlur={saveEnsureAdminPassword} />
                <span>{ensureAdminPassword.info}</span>
            </p>
            <button onClick={handleReg}>注册</button>
            <div>{regState}</div>
        </div>
    )

}
